[LeetCode] 654 - Maximum Binary Tree

題意

建造最大二元樹。

解法

照題目描述模擬即可。

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var constructMaximumBinaryTree = function(nums) {
const build = (left, right) => {
if ( left > right ) return null;
let max = -1, maxIndex = left;
for ( let i = left; i <= right ; i ++ ){
if ( nums[i] > max ){
max = nums[i];
maxIndex = i;
}
}
const node = new TreeNode(nums[maxIndex]);
node.left = build(left, maxIndex-1);
node.right = build(maxIndex+1, right);
return node;
}
return build(0, nums.length - 1);
};